package com.pic.others.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pic.common.constants.UserVipConstants;
import com.pic.common.utils.R;
import com.pic.common.utils.UserContext;
import com.pic.others.config.minio.MinIOConfigProperties;
import com.pic.others.config.minio.MinIOUtil;
import com.pic.others.constants.category.ConnectionFlaskConstant;
import com.pic.others.domain.dto.flask.FlaskSimilarResDTO;
import com.pic.others.domain.po.Picture;
import com.pic.others.domain.po.RecommendSimilarPicture;
import com.pic.others.domain.po.Recyle;
import com.pic.others.domain.po.User;
import com.pic.others.mapper.PictureMapper;
import com.pic.others.mapper.RecommendSimilarPictureMapper;
import com.pic.others.mapper.RecyleMapper;
import com.pic.others.service.IRecommendSimilarPictureService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pic.others.utils.ConnectionFlaskUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author koshi
 * @since 2023-12-24
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class RecommendSimilarPictureServiceImpl extends ServiceImpl<RecommendSimilarPictureMapper, RecommendSimilarPicture> implements IRecommendSimilarPictureService {

    private final MinIOUtil minIOUtil;
    private final MinIOConfigProperties minIOConfigProperties;
    private final UserServiceImpl userService;
    private final PictureServiceImpl pictureService;
    private final RecyleMapper recyleMapper;
    private final RecyleServiceImpl recyleService;
    @Value("${minio.bucket}")
    private String bucketName;

    @Override
    public R<Map<LocalDate, List<RecommendSimilarPicture>>> getManySimilar() {
        Long userId = UserContext.getUser();
        if(userId==null){
            return R.error("用户未登录");
        }
        List<RecommendSimilarPicture> recommendSimilarPictureList = lambdaQuery().eq(RecommendSimilarPicture::getUserId, userId).list();
        Map<LocalDate,List<RecommendSimilarPicture>>map=new HashMap<>();
        List<RecommendSimilarPicture>recommendSimilarPictures=lambdaQuery().select()
                .eq(RecommendSimilarPicture::getUserId,userId).list();
        for(RecommendSimilarPicture picture:recommendSimilarPictures){
            LocalDate localDate=LocalDate.from(picture.getDateTime());
            if(!map.containsKey(localDate)){
                map.put(localDate,new ArrayList<RecommendSimilarPicture>());
            }
            map.get(localDate).add(picture);
        }
        return R.success(map);
    }

    @Override
    public R<String> deleteByAdvise(List<Long> ids) {
        long userId = UserContext.getUser();
        List<RecommendSimilarPicture> pictures = lambdaQuery().in(RecommendSimilarPicture::getRecommandId, ids).list();
        for(RecommendSimilarPicture picture:pictures){
            Picture pic=pictureService.getById(picture.getPictureId());
            LocalDateTime now = LocalDateTime.now();
            User user = userService.getById(userId);
            LocalDateTime recyleTime = now.plusDays(user.getIsvip()
                    ? UserVipConstants.vip.VIP_RECYLE_TIME
                    : UserVipConstants.usual.USUAL_RECYLE_TIME);
            Recyle recyle = new Recyle();
            recyle.setDateTime(now);
            recyle.setPicId(picture.getPictureId());
            recyle.setDateTime(now);
            recyle.setUserId(userId);
            recyle.setLocate(picture.getLocate());
            recyle.setDate(picture.getDateTime());
            log.info("recyleTime:{}",recyleTime);
            recyle.setRecyleTime(recyleTime);
            boolean flag = removeById(picture.getPictureId());
            removeById(picture.getRecommandId());
                recyleMapper.insert(recyle);
            }

            return R.success("删除成功");

        }





    @Override
    public R<Map<Long, List<RecommendSimilarPicture>>> initRecommand() {
        Long userId = UserContext.getUser();

        List<Picture> pictures = Collections.unmodifiableList(pictureService.lambdaQuery().eq(Picture::getUserId, userId).list());
        if (pictures == null || pictures.isEmpty()) {
            return R.error("图片为空");
        }

        Map<Long, List<RecommendSimilarPicture>> map = new HashMap<>();
        boolean[] flags = new boolean[pictures.size()];

        for (int i = 0; i < pictures.size(); i++) {
            int k = 0;
            if (!flags[i]) {
                for (int j = i + 1; j < pictures.size(); j++) {
                    if (!flags[j]) {
                        FlaskSimilarResDTO resDTO = new FlaskSimilarResDTO(pictures.get(i).getLocate(), pictures.get(j).getLocate());
                        try {
                            String data = ConnectionFlaskUtils.getConnectionFlask(
                                    ConnectionFlaskConstant.urlPath.GET_SIMILAR_PICTURE,
                                    ConnectionFlaskConstant.method.POSTMAPPING,
                                    "data", resDTO);
                            log.info(data);
                            if ("True".equals(data)) {
                                RecommendSimilarPicture similarPicture = new RecommendSimilarPicture();
                                similarPicture.setUserId(userId);
                                similarPicture.setPictureId(pictures.get(j).getPicId());
                                similarPicture.setLocate(pictures.get(j).getLocate());
                                save(similarPicture);
                                map.putIfAbsent((long) i, new ArrayList<>());
                                map.get((long) i).add(similarPicture);
                                k++;
                                flags[j] = true;
                            }
                        } catch (Exception e) {
                            log.error("与 Flask 通信时发生异常: {}", e.getMessage(), e);
                            // 处理异常，可能需要根据具体情况进行回滚等操作
                        }
                    }
                }
                if (k > 0) {
                    RecommendSimilarPicture similarPicture2 = new RecommendSimilarPicture();
                    similarPicture2.setUserId(userId);
                    similarPicture2.setPictureId(pictures.get(i).getPicId());
                    similarPicture2.setLocate(pictures.get(i).getLocate());
                    save(similarPicture2);
                    map.get((long) i).add(similarPicture2);
                }
            }
        }

        return R.success(map);
    }

}
